package cn.jaye.fabric.controller;

import cn.jaye.fabric.application.BlockApplicationService;
import cn.jaye.fabric.application.command.block.InfoBlockCommand;
import cn.jaye.fabric.application.command.block.ListBlockCommand;
import cn.jaye.fabric.common.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Jaye
 * @create 2018-05-03 11:47
 */
@RestController
@RequestMapping("chain")
public class ChainController {

    @Autowired
    private BlockApplicationService blockApplicationService;


    @PostMapping("block/list")
    public String listAll(HttpServletRequest request, @RequestBody ListBlockCommand listBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.listBlockChainInfo(listBlockCommand.getChannelName()));
    }

    @PostMapping("block/base/list")
    public String listBaseInfo(HttpServletRequest request, @RequestBody ListBlockCommand listBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.listBlockChainBaseInfo(listBlockCommand.getChannelName()));
    }

    @PostMapping("info")
    public String info(HttpServletRequest request, @RequestBody InfoBlockCommand infoBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.getBlockChainInfo(infoBlockCommand.getChannelName()));
    }

    @PostMapping("block/info/hash")
    public String infoBlockByHash(@RequestBody InfoBlockCommand infoBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.getBlockByHash(infoBlockCommand.getChannelName(), infoBlockCommand.getDataHash()));
    }

    @PostMapping("block/info/number")
    public String infoBlockByNumber(@RequestBody InfoBlockCommand infoBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.getBlockByNumber(infoBlockCommand.getChannelName(), infoBlockCommand.getBlockNumber()));
    }

    @PostMapping("info/txid")
    public String infoBlockBytxId(@RequestBody InfoBlockCommand infoBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.getBlockByTxId(infoBlockCommand.getChannelName(), infoBlockCommand.getTxId()));
    }

    @PostMapping("transaction/info/txid")
    public String infoTransactionByHash(@RequestBody InfoBlockCommand infoBlockCommand) throws Exception {
        return ResultUtil.success(blockApplicationService.getTransaction(infoBlockCommand.getChannelName(), infoBlockCommand.getTxId()));
    }
}
